package com.example.springboot.service;

import cn.hutool.core.util.RandomUtil;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.repository.UserRepository;
//import com.example.springboot.utils.TokenUtils;
import com.example.springboot.utils.TokenUtils;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.util.List;
import java.util.Objects;

@Service
public class UserService {
    @Resource
    UserRepository userRepository;

    @Resource
    UserMapper userMapper;

    public List<User> findAll() {
        return userRepository.findAll();
    }

    @SneakyThrows
    public User login(User user){
        // 查询数据库中是否存在该用户
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser == null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户名或密码错误");
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户名或密码错误");
        }
        String token= TokenUtils.createToken(dbUser.getId().toString(),dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }
    @SneakyThrows
    public User register(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser != null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户名已存在");
        }
        user.setName(user.getName());
        userMapper.insert(user);
        return user;
    }

    public int update(User user) {
        return userMapper.update(user);
    }
}
